// 数据请求
const _baseUrl = 'http://localhost:9991/'; 
const _imgBaseUrl = 'http://localhost:9991/'; 

let $httpVue = null;
const init = function(vue) {
	$httpVue = vue;
}

//当前token快要过期时，用现有的token换成一个新的token
const getNewToken = function(callBack) {
	uni.request({
		url: _baseUrl + "api/User/replaceToken",
		data: {},
		method: "POST",
		async: false,
		header: {
			'content-type': 'application/json'
		},
		success: function(x) {
			if (x.status) {
				let userInfo = $httpVue.$store.getters.getUserInfo();
				userInfo.token = x.data;
				//currentToken = x.data;
				$httpVue.$store.commit('setUserInfo', userInfo);
				callBack();
			} else {
				console.log(x.message);
				toLogin();
			}
		},
		errror: function(ex) {
			console.log(ex);
			toLogin();
		}
	});

}

const Post = function(options, calback, a, b, c) {
	//debugger;
	//
	let token = ""; //getToken();
	// if (options.url != "api/user/login") {
	// 	let userInfo = $httpVue.$store.getters.getUserInfo();
	// 	token = 'Bearer ' + userInfo.token;
	// }

	uni.request({
		url: _baseUrl + options.url,
		data: JSON.stringify(options.data),
		method: "POST",
		header: {
			'content-type': 'application/json',
			'Authorization': token
		},
		success: function(res) {
			var ret = res.data;
			calback(ret, a, b, c);
		},
		errror: function(res) {
			calback(ret, a, b, c);
		}
	});
}

//处理图片路径
const setImgUrl = function(url,t="sm") {
	var ret;
	if (url != undefined || url == "") {
		//统一用小图地址
		if(t=="sm"){
			url=url.replace(/images/g, "imagesSmaill");
		}
		
		ret = _imgBaseUrl + url.replace(/\\/g, "/");
	}
	
	return ret;
}

//获取本地存储
const getItemLocalstorage = function(itemName) {
	let ret = "";
	// if (localStorage != undefined && localStorage.length > 0) {
	// 	var cartData = localStorage.getItem(itemName);
	// 	if (cartData != null) {
	// 		ret = JSON.parse(cartData);
	// 	}
	// }
	// 同步方式获取数据， 阻塞形式，如果做完了的话代码才会向下进行
	try {
		const value = uni.getStorageSync(itemName);
		if (value) {
			ret = typeof(value) == "object" ? value : JSON.parse(value);
			//console.log("const value = uni.getStorageSync('name') 同步获取 = " + value);
		}
	} catch (e) {
		//TODO handle the exception
	};
	return ret;
}

//保存本地存储
const setItemLocalstorage = function(key, value) {
	//localStorage.setItem(key, value);
	//数据缓存 同步 一定要用try catch 包裹
	try {
		uni.setStorageSync(key, value);
	} catch (e) {
		//TODO handle the exception
	};
}

const getTime = function() {

	var date = new Date(),
		year = date.getFullYear(),
		month = date.getMonth() + 1,
		day = date.getDate(),
		hour = date.getHours() < 10 ? "0" + date.getHours() : date.getHours(),
		minute = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes(),
		second = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
	month >= 1 && month <= 9 ? (month = "0" + month) : "";
	day >= 0 && day <= 9 ? (day = "0" + day) : "";
	var timer = year + '-' + month + '-' + day + ' ' + hour + ':' + minute + ':' + second;
	return timer;
}

//另外，也可以将从数据库获取到的datetime数据类型的字段作为参数传入该方法,如：

const parseServerTime = function(time) {

	var date = new Date(time),
		year = date.getFullYear(),
		month = date.getMonth() + 1,
		day = date.getDate(),
		hour = date.getHours() < 10 ? "0" + date.getHours() : date.getHours(),
		minute = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes(),
		second = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
	month >= 1 && month <= 9 ? (month = "0" + month) : "";
	day >= 0 && day <= 9 ? (day = "0" + day) : "";
	var timer = year + '-' + month + '-' + day + ' ' + hour + ':' + minute + ':' + second;
	return timer;
}

// 两点间距离
const distance = function(la1, lo1, la2, lo2) {
      var La1 = (la1 * Math.PI) / 180.0
      var La2 = (la2 * Math.PI) / 180.0
      var La3 = La1 - La2
      var Lb3 = (lo1 * Math.PI) / 180.0 - (lo2 * Math.PI) / 180.0
      var s =
        2 *
        Math.asin(
          Math.sqrt(
            Math.pow(Math.sin(La3 / 2), 2) +
              Math.cos(La1) * Math.cos(La2) * Math.pow(Math.sin(Lb3 / 2), 2)
          )
        )
      s = s * 6378.137 //地球半径
      s = Math.round(s * 10000) / 10000
      return s
    }


export default {
	init,
	Post,
	setItemLocalstorage,
	getItemLocalstorage,
	getNewToken,
	setImgUrl, //将图片地址转换成合法格式
	_baseUrl,
	_imgBaseUrl,
	getTime,
	parseServerTime,
	distance
}
